package com.map.core.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Slf4j
public class ZipUtils {
    public static final Integer DEFAULT_BUFF_SIZE = 500;
    public static void compress(String srcPath, String destPath,boolean dirFlag)  throws IOException {

        compress(new File(srcPath), new File(destPath), dirFlag);
    }

    public static void compress(File srcFile, File destFile, boolean dirFlag) throws IOException {
        compress(srcFile, new ZipOutputStream(new FileOutputStream(destFile)), dirFlag);
    }

    public static void compress(File srcFile, ZipOutputStream zos, boolean dirFlag) throws IOException {
        // 需要解压的压缩文件对象
        // 压缩输出流
        // 是否在压缩文件时创建一个父文件夹后再压缩
        if (srcFile.isDirectory()) {
            if (dirFlag) {
                doCompress(zos, srcFile, srcFile.getCanonicalPath().substring(srcFile.getName().length()));
            } else {
                doCompress(zos, srcFile, srcFile.getCanonicalPath());
            }
        } else {
            doCompress(zos, srcFile, srcFile.getCanonicalPath().substring(srcFile.getName().length()));
        }
        try {
            zos.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 适用于只含有一层文件夹的目录（共两层）
     * @param zos
     * @param file
     * @param srcDir
     * @throws IOException
     */
    public static void doCompress(ZipOutputStream zos, File file, String srcDir) throws IOException {
        if (file.isDirectory()) {
            // 递归循环，只压缩其中所有文件
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                doCompress(zos, files[i], srcDir);
            }
        } else {
            // 进行文件压缩的操作
            byte[] buff = new byte[DEFAULT_BUFF_SIZE];
            int len = 0;
            try {
                BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
                zos.putNextEntry(new ZipEntry(file.getCanonicalPath().substring(srcDir.length())));

                while ((len = in.read(buff, 0, DEFAULT_BUFF_SIZE)) != -1) {
                    zos.write(buff, 0, len);
                }
                in.close();
                zos.flush();
                zos.closeEntry();
            } catch (FileNotFoundException e) {
                log.error(""+ e);
            } catch (IOException e) {
                log.error("error when"+ len);
                e.printStackTrace();
                throw e;
            }


        }
    }
}
